import collections
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def convertBST(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        val = 0
        node = root
        stack = collections.deque([node])
        while stack:
            node = stack[-1]
            while node.right:
                node = node.right
                stack.append(node)
            while stack:
                node = stack.pop()
                node.val += val
                val = node.val
                if node.left:
                    break
            if node.left:
                stack.append(node.left)
        return root




